<?php

// +----------------------------------------------------------------------
// Device固定资产列表
// +----------------------------------------------------------------------

namespace app\document\controller;
error_reporting(0);
use app\document\service\DataService;
use library\Controller;
use library\tools\Data;
use think\Db;
use think\Response;
use think\request;
use think\facade\Config;

/**
 * 固定资产
 */
class Device extends Controller
{

    /**
     * 绑定当前数据表
     * @var string
     */
    protected $table = 'Device';

    /**
     * 固定资产列表
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
    	$this->title ='新增资产';
    	$allusers = session('admin_user')['nickname'];

        $this->_query($this->table)->like('devicename,username,localtion')
        	 //->where("username LIKE '%".$allusers."%' ")
        	 ->dateBetween('buytime')
        	 ->equal('status')->order('id DESC')->page();
    }

    /**
     * 维修记录
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function record()
    {
        $id =intval($this->request->param('id'));
        $rs =Db::table('Device')->where('id',$id)->find();
        $this->_query('Repair')
             ->field('*')
             ->like('devicename,username,localtion')
             ->where("docid ='".$id."' ")
             //->dateBetween('buytime')
             //->equal('status')
             ->order('id DESC')->page();

        $this->assign('devicename' , $rs['devicename']);  

    }


    /**
     * 编辑维修记录
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit_record()
    {

            $id =$this->request->param('id');

            $ids =explode(',' , $id);

            if(count($ids) > 1){
                $this->error('强制办结，只能一次选择一条记录！' );
            }
            
            print_r($ids);
            die();


        $this->title = '编辑维修记录';
        $this->applyCsrfToken();
        if ($this->request->isGet()) {
            $id =$this->request->param('id');

            $ids =explode(',' , $id);

            if(count($ids) > 1){
                $this->error('强制办结，只能一次选择一条记录！' );
            }

            print_r($ids);
            die();
            if(count($id)>1){
                $this->error('每次只能编辑一条记录');
            }
            $rs =Db::table('Device')->where('id',$id)->find();
            $this->assign('vo' , $rs);
            $this->fetch('repair');
            //$this->_form($this->table, 'repair');
        }else{
            $post = $this->request->post();
            $this->_form('repair', 'repair');
        } 

    }




    /**
     * 新增资产
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
    	$this->title = '新增';
    	$allusers = session('admin_user')['nickname'];

    	//echo $allusers;

    	if ($this->request->isPost()) {
    		list($data1, $string) = [$this->request->post(), []];

    		$data1['docauthor'] =$allusers;
    		$data1['addtime'] =time();

    		$ids =Db::name('Device')->strict(false)->insertGetId($data1);

    		//插入附件
        	list($post, $datas) = [$this->request->post(), []];
        	if (isset($post['fileurl']) && is_array($post['fileurl'])) {
        		$files =[];
                foreach (array_keys($post['fileurl']) as $key) {
                	array_push($files, [
	                    'docid'     => $ids,
	                    'username'    => $post['docauthor'],
	                    'original_name' => $post['original_name'][$key],
	                    'fileext'   => $post['fileext'][$key],
	                    'filesize'  => $post['filesize'][$key],
	                    'fileurl'   => $post['fileurl'][$key],
	                    'filename'  => $post['filename'][$key],
	                    'md5code'   => $post['md5code'][$key],
	                    'sha1code'  => $post['sha1code'][$key],
                        'flag'      => 'device',
                	]);
                }
                if (!empty($files)) {
                    Db::name('Attachment')->insertAll($files);
                }
        	}

        	$this->success('新增数据保存成功!', '/admin.html#/document/device/index.html?spm=m-73-97-98');
    	}

    	$list = Db::name('SystemUser')->field('id,username,nickname')->where('id >10000')->where(['status'=>'1'])->select();
    	$str ='';
    	foreach ($list as &$value) {
    		$str .="{name:'".$value['nickname']."', value: '".$value['nickname']."'},\r\n";
    	}
    	$username ='';
    	$this->assign('username' , $username);  
    	$this->assign('str' , $str);  
		$this->_form($this->table, 'form');
    }


    /**
     * 编辑信息
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {
        $this->title = '编辑信息';

        $nickname = session('admin_user')['nickname'];

    	$id =intval($this->request->param('id'));
    	$rs =Db::table('Device')->where('id',$id)->find();

    	//-编辑资料保存
    	if ($this->request->isPost()) {
    		list($data1, $string) = [$this->request->post(), []];
			Db::name('Device')
			    ->where('id', $data1['id'])
			    ->strict(false)
			    ->data($data1)
			    ->update();

        	list($post, $datas) = [$this->request->post(), []];
        	if (isset($post['fileurl']) && is_array($post['fileurl'])) {
        		$files =[];
                foreach (array_keys($post['fileurl']) as $key) {
                	array_push($files, [
	                    'docid'     => $data1['id'],
	                    'username'    => $post['docauthor'],
	                    'original_name' => $post['original_name'][$key],
	                    'fileext'   => $post['fileext'][$key],
	                    'filesize'  => $post['filesize'][$key],
	                    'fileurl'   => $post['fileurl'][$key],
	                    'filename'  => $post['filename'][$key],
	                    'md5code'   => $post['md5code'][$key],
	                    'sha1code'  => $post['sha1code'][$key],
                        'flag'      => 'device',
                	]);
                }
                if (!empty($files)) {
                    Db::name('Attachment')->insertAll($files);
                }
        	}

        	$this->success('编辑成功，正在保存!', '/admin.html#/document/device/index.html?spm=m-73-97-98');

    	}

    	//-基本信息-----------------
    	$files =Db::table('Attachment')->where(['docid'=>$id, 'flag'=>'device'])->select();

        //显示使用人员
        $username =$this->showUser($rs['username']);

    	$list = Db::name('SystemUser')->field('id,username,nickname')->where('id >10000')->where(['status'=>'1'])->select();
    	$str ='';
    	foreach ($list as &$value) {
    		$str .="{name:'".$value['nickname']."', value: '".$value['nickname']."'},\r\n";
    	}


    	$this->assign('id' , $id);
    	$this->assign('vo' , $rs);
    	$this->assign('docauthor' , $rs['docauthor']);
    	$this->assign('files' , $files);
    	$this->assign('str' , $str);
    	$this->assign('username' , $username);
        $this->_form($this->table, 'form');

    }

    public function repair()
    {
    	$this->title = '添加维修记录';
    	$this->applyCsrfToken();
		if ($this->request->isGet()) {
			$this->_form($this->table, 'repair');
		}else{
			$post = $this->request->post();
			$this->_form('repair', 'repair');
		}
    }

    private function showUser($data)
    {
        if($data !=''){
            $tmp1 = explode(',' , $data);
            $str1 ='';
            if(is_array($tmp1)){
                foreach ($tmp1 as $key => &$v) {
                    $str1 .="'".$v."',";
                }

            }else{
                $str1 =$data;
            }
            $str1 =rtrim($str1 , ',');
        }
        return $str1;
    }

	public function filelist()
	{
		$this->title = '文件列表';
		$this->fetch();
	}

     public function upload()
    {
        if($this->request->file('file')){
            $file       = $this->uploadfile('file','' ,[] , session('admin_user')['id']);
            if ($file) {
                echo json_encode($file);
            } else {
                echo json_encode($file);
            }
        }
    }


    public function uploadfile($name, $path = '', $validate = [], $user_id = 0)
    {
        $config = config('attchment');
        $file   = request()->file($name);
        if ($file) {
            $file_path = $config['path'] . $path;
            $file_url  = $config['url'] . $path;
            $validate  = array_merge($config['validate'], $validate);
            $info      = $file->validate($validate)->move($file_path);
            if ($info) {
                $file_info = [
                	'code'          => 0 ,
                    'user_id'       => $user_id,
                    'original_name' => $info->getInfo('name'),
                    'save_name'     => $info->getFilename(),
                    'save_path'     => str_replace("\\", "/",$file_path . $info->getSaveName()),
                    'extension'     => $info->getExtension(),
                    'mime'          => $info->getInfo('type'),
                    'size'          => $info->getSize(),
                    'md5'           => $info->hash('md5'),
                    'sha1'          => $info->hash(),
                    'url'           => str_replace("\\", "/",$file_url . $info->getSaveName())
                ];
                return $file_info;
            } else {
                return $file->getError();
            }
        } else {
            return '无法获取文件';
        }
        return false;
    }


    public function zipfile()
    {
        if ($this->request->isGet()) {
            $data =$this->request->param();
            $id =intval($data['id']);

            if($id <= 0){
                $res =[];
                $res['code'] =201;
                $res['msg'] ='参数错误!' ;

                echo json_encode($res); 
                die();
            }

            $file_list =Db::table('Attachment')
            ->where( "  docid='".$data['id']."' AND flag='device' ")
            ->select();
            if( count($file_list) == 0){
                $res =[];
                $res['code'] =202;
                $res['msg'] ='文件列表为空!' ;

                echo json_encode($res); 
                die();
            }

            $res =[];
            $res['code'] =200;
            $res['msg'] ='成功!' ;
            $path =dirname( $file_list['0']['fileurl']);
            $res['data'] = $path;
            $res['files'] = $file_list;
           

            $outputFilename =str_replace("\\","/", ROOTPATH . $path .'/Device_'.$id.'.zip' ); //ROOTPATH . $path .'/Device_'.$id.'.zip';
            $res['outputFilename'] = $outputFilename;
            if(file_exists($outputFilename)){
                @unlink($outputFilename);
            }
            //echo json_encode($res);
            //    die();   
            $zipFile = new \PhpZip\ZipFile();
            try{
                $zipFile = new \PhpZip\ZipFile();
                foreach ($file_list as $v) {
                    $zipFile->addFile(ROOTPATH.$v['fileurl']);
                }
                $zipFile->saveAsFile($outputFilename); // save the archive to a file
                $zipFile->close(); // close archive  

            }
            catch(\PhpZip\Exception\ZipException $e){
                $res =[];
                $res['code'] =203;
                $res['msg'] ='发生未知错误，请联系管理员!' ;
                echo json_encode($res);
                die();                 
            }
            finally{
                $zipFile->close();
            }

            $res['down']  =$path .'/Device_'.$id.'.zip';

            echo json_encode($res);
            die(); 
        }
    } 



}
